package com.north.light.libbilibilidfm;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;

import androidx.annotation.NonNull;

import com.north.light.libbilibilidfm.base.BiliDanmakuParser;
import com.north.light.libbilibilidfm.base.BiliDanmakuView;
import com.north.light.libbilibilidfm.utils.DoExamCusBulletCollectionsUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDisplayer;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

/**
 * FileName: DoExamCusBulletView
 * Author: lzt
 * Date: 2022/12/12 15:08
 * 做题弹幕类--继承哔哩哔哩弹幕库
 */
@Deprecated
public class DoExamCusBulletView extends BiliDanmakuView implements DoExamCusBulletViewApi {
    private List<DoExamCusBulletInfo> dataList = new ArrayList<>();
    //当前播放数据的位置
    private int playIndex = 0;
    private DanmakuContext mDanMuContext;
    private BaseDanmakuParser mDanMuParser;
    //播放弹幕handler
    //检查标识
    private static final int HANDLER_CHECK = 0x0001;
    //检查数据间距
    private static final long HANDLER_CHECK_INTERVAL = 100L;
    //弹幕延时出现控制值
    private static final long DELAY_TIME = 20L;
    //外部标识
    private String mIdentify = this.getClass().getSimpleName();
    //弹幕tag key
//    private static final int TAG_KEY = 1;

    private Handler mBulletHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case HANDLER_CHECK:
                    if (!isPrepared()) {
                        mBulletHandler.sendEmptyMessageDelayed(HANDLER_CHECK, HANDLER_CHECK_INTERVAL);
                        return;
                    }
                    if (!DoExamCusBulletCollectionsUtils.isEmpty(dataList) && dataList.size() > playIndex) {
                        DoExamCusBulletInfo dataInfo = dataList.get(playIndex);
                        setBullet(dataInfo);
                        playIndex++;
                    }
                    mBulletHandler.sendEmptyMessageDelayed(HANDLER_CHECK, HANDLER_CHECK_INTERVAL);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public DoExamCusBulletView(Context context) {
        super(context);
    }

    public DoExamCusBulletView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DoExamCusBulletView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


//    @Override
//    public void onWindowFocusChanged(boolean hasWindowFocus) {
//        super.onWindowFocusChanged(hasWindowFocus);
//        //初始化完成并存在弹幕，则启动焦点变动暂停
//        if (isPrepared() && hadBullet()) {
//            if (hasWindowFocus) {
//                Log.d(TAG, mIdentify + "onWindowFocusChanged: resume");
//                resume();
//            } else {
//                Log.d(TAG, mIdentify + "onWindowFocusChanged: pause");
//                pause();
//            }
//        }
//    }


    /**
     * 显示一条弹幕
     */
    private void setBullet(DoExamCusBulletInfo bulletInfo) {
        if (bulletInfo == null) {
            return;
        }
        BaseDanmaku danMuKu = mDanMuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
        if (danMuKu == null) {
            return;
        }
        try {
            danMuKu.text = bulletInfo.getContent();
            danMuKu.padding = 5;
            //可能会被各种过滤器过滤并隐藏显示
            danMuKu.priority = 0;
            danMuKu.isLive = false;
//            danMuKu.setTime(getCurrentTime() + doExamCusBulletInfo.getShowTime());
            danMuKu.setTime(bulletInfo.getShowTime() + DELAY_TIME);
            danMuKu.textSize = bulletInfo.getTextSize() * (mDanMuParser.getDisplayer().getDensity() - 0.6f);
            if (bulletInfo.isOwner()) {
                danMuKu.textColor = Color.RED;
            } else {
                danMuKu.textColor = Color.WHITE;
            }
            danMuKu.textShadowColor = Color.BLACK;
//            danMuKu.setTag(TAG_KEY, bulletInfo);
            addDanmaku(danMuKu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否存在数据
     */
    private boolean hadBullet() {
        return DoExamCusBulletCollectionsUtils.isEmpty(dataList);
    }

    /**
     * 初始化
     */
    private void init() {
        clean();
        release();
        mDanMuParser = BiliDanmakuParser.createParser(null);
        HashMap<Integer, Integer> maxLinesPair = new HashMap<Integer, Integer>();
        //滚动弹幕最大显示3行
        maxLinesPair.put(BaseDanmaku.TYPE_SCROLL_RL, 3);
        HashMap<Integer, Boolean> overlappingEnablePair = new HashMap<Integer, Boolean>();
        overlappingEnablePair.put(BaseDanmaku.TYPE_SCROLL_RL, false);
        overlappingEnablePair.put(BaseDanmaku.TYPE_FIX_TOP, false);
        mDanMuContext = DanmakuContext.create();
        mDanMuContext.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_SHADOW, 3)
                .setDuplicateMergingEnabled(false)
                .setScrollSpeedFactor(1.2f)
                .setScaleTextSize(1.2f)
                //绘制背景使用BackgroundCacheStuffer
//                .setCacheStuffer(new BackgroundCacheStuffer(), null)
                .setMaximumLines(maxLinesPair)
                .preventOverlapping(overlappingEnablePair)
                .setDanmakuMargin(40);

        prepare(mDanMuParser, mDanMuContext);
        showFPS(false);
        enableDanmakuDrawingCache(true);
        setCallback(new DrawHandler.Callback() {
            @Override
            public void prepared() {
                Log.d(TAG, mIdentify + "prepared");
                start();
                seek(0L);
                //开始显示数据
                startHandlerCheck();
            }

            @Override
            public void updateTimer(DanmakuTimer timer) {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {
                Log.d(TAG, mIdentify + "danmakuShown");
            }

            @Override
            public void drawingFinished() {
                Log.d(TAG, mIdentify + "drawingFinished");
            }
        });
    }

    /**
     * 绘制背景(自定义弹幕样式)
     */
    private static class BackgroundCacheStuffer extends SpannedCacheStuffer {
        // 通过扩展SimpleTextCacheStuffer或SpannedCacheStuffer个性化你的弹幕样式
        final Paint paint = new Paint();

        @Override
        public void measure(BaseDanmaku danmaku, TextPaint paint, boolean fromWorkerThread) {
//            danmaku.padding = 10;  // 在背景绘制模式下增加padding
            super.measure(danmaku, paint, fromWorkerThread);
        }

        @Override
        public void drawBackground(BaseDanmaku danmaku, Canvas canvas, float left, float top) {
            //判读当前弹幕是否为自己发的
//            if (danmaku.getTag(TAG_KEY) instanceof DoExamCusBulletInfo) {
//                DoExamCusBulletInfo doExamCusBulletInfo = (DoExamCusBulletInfo) danmaku.getTag(TAG_KEY);
//                if (doExamCusBulletInfo != null && doExamCusBulletInfo.isOwner()) {
//                    paint.setColor(Color.WHITE);
//                    paint.setStyle(Paint.Style.STROKE);
//                    canvas.drawRoundRect(left + 2, top + 2, left + danmaku.paintWidth - 2,
//                            top + danmaku.paintHeight - 2, 10, 10, paint);
//                }
//            }

//            paint.setColor(Color.WHITE);
//            paint.setStyle(Paint.Style.STROKE);
//            canvas.drawRoundRect(left + 2, top + 2, left + danmaku.paintWidth - 2,
//                    top + danmaku.paintHeight - 2, 10, 10, paint);
        }

        @Override
        public void drawStroke(BaseDanmaku danmaku, String lineText, Canvas canvas, float left, float top, Paint paint) {
            // 禁用描边绘制
        }
    }

    /**
     * 开始检查
     */
    private void startHandlerCheck() {
        mBulletHandler.removeMessages(HANDLER_CHECK);
        mBulletHandler.sendEmptyMessage(HANDLER_CHECK);
    }

    /**
     * 显示
     *
     * @param resetData 是否重置数据
     */
    private void resetData(boolean resetData) {
        Log.d(TAG, mIdentify + "show");
        if (!DoExamCusBulletCollectionsUtils.isEmpty(dataList)) {
            //排序
            Collections.sort(dataList, new Comparator<DoExamCusBulletInfo>() {
                @Override
                public int compare(DoExamCusBulletInfo o1, DoExamCusBulletInfo o2) {
                    return (int) (o1.getShowTime() - o2.getShowTime());
                }
            });
            //数据时间去重--关键！！！如果时间重复，数据会出现丢失的情况
            for (int i = 0; i < dataList.size(); i++) {
                long showTime = dataList.get(i).getShowTime() + i;
                dataList.get(i).setShowTime(showTime);
            }
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Log.d(TAG, mIdentify + "onAttachedToWindow");
        init();
    }

    @Override
    protected void onDetachedFromWindow() {
        clean();
        Log.d(TAG, mIdentify + "onDetachedFromWindow");
        super.onDetachedFromWindow();
    }

    //外部调用------------------------------------------------------------------------------------

    @Override
    public void setData(List<DoExamCusBulletInfo> doExamList) {
        clean();
        //数据处理
        dataList.clear();
        dataList.addAll(DoExamCusBulletCollectionsUtils.cloneListSer(doExamList));
        seek(0L);
        playIndex = 0;
        resetData(true);
        startHandlerCheck();
    }

    @Override
    public void addBullet(DoExamCusBulletInfo info) {
        if (info == null) {
            return;
        }
        dataList.add(playIndex, DoExamCusBulletCollectionsUtils.cloneObjectSer(info));
        resetData(false);
        startHandlerCheck();
    }

    @Override
    public void clean() {
        mBulletHandler.removeCallbacksAndMessages(null);
        playIndex = 0;
    }

    @Override
    public void seek(long time) {
        seekTo(time);
    }

    @Override
    public void replay() {
        seek(0);
    }

    @Override
    public void setIdentify(String key) {
        this.mIdentify = key;
    }

    @Override
    public void setShow(boolean show, boolean autoResume) {
        if (show) {
            if (autoResume && isPrepared()) {
                resume();
            }
            show();
        } else {
            if (autoResume && isPrepared()) {
                pause();
            }
            hide();
        }
    }


}
